import React, { useRef, useEffect } from 'react';
import { isEmpty } from 'lodash';
import { Helmet } from 'react-helmet';
import useMediaRecorder from '@wmik/use-media-recorder';
import SessionTrackPlayer from './SessionTrackPlayer';
import { useReplay, useUpload } from '../../service';

const Player = ({ events, width, height, upload }) => {
  const ref = useRef();

  let { stopRecording, startRecording } = useMediaRecorder({
    recordScreen: true,
    mediaRecorderOptions: { mimeType: 'video/webm' },
    mediaStreamConstraints: { audio: false, video: true },
    onStop: async (blob) => {
      await upload(blob)
      await window.closeBrowser && window.closeBrowser()
    }
  });

  useEffect(() => {
    if (ref.current) {
      const { player } = ref.current;
      player.addEventListener('finish', stopRecording);
      startRecording().then(() => {
        player._state.replayer.play();
      });
    }
    // startRecording, stopRecording 不能作为依赖
    // 因为 useMediaRecorder 每次都会返回不同的函数，重新执行会导致多次录屏
  }, [ref.current]);

  return (
    <SessionTrackPlayer
      ref={ref}
      autoPlay={false}
      events={events}
      width={width}
      height={height}
    />
  );
};

const Capture = ({ match }) => {
  const session = match.params.id;
  const [loading, replay] = useReplay(session);
  const [uploading, upload] = useUpload(session);
  const { events, width, height } = replay;

  if (isEmpty(events) || loading) {
    return null;
  }

  return (
    <>
      <Helmet>
        <title>z-track</title>
      </Helmet>
      <Player events={events} upload={upload} width={width} height={height} />
    </>
  );
};

export default Capture;
